Android14 显示系统剖析4 ———— 显示配置信息获取与 SurfaceControl 初始化

6/12/2024

本文基于 aosp android-14.0.0_r15 版本讲解。

# 1. 回顾

上一节,我们分析了 Native App 与 SurfaceFinger 建立 Binder 通信的过程:

  • SurfaceFlinger 进程中提供了 SurfaceFlinger Binder 服务,SurfaceFlingerAIDL Binder 服务和一个名为 Client 的匿名 Binder 服务

20240701160200

整个 binder 通信通道的建立过程:

  • App 向 ServiceManager 查询 SurfaceFlingerAIDL 服务,获取到服务的代理端对象
  • 接着远程调用 SurfaceFlingerAIDL 服务的 createConnection 函数,获取到 Client 匿名服务的代理端对象
  • App 想要调用 SurfaceFlinger 相关的功能,可以远程调用 Client 服务,Client 服务中具体的功能再委托给 SurfaceFlinger 来实现。

20240701160254

# 2. 整体流程

我们接着看示例程序的后续代码:

int main(int argc, char ** argv) {

    // ......


    // 获取到显示设备的 ID
    // 返回的是一个 vector,因为存在多屏或者投屏等情况
    const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds();
    if (ids.empty()) {
        ALOGE("Failed to get ID for any displays\n");
        return;
    }   

    //displayToken 是屏幕的索引
    sp<IBinder> displayToken = nullptr;
    
    // 示例仅考虑只有一个屏幕的情况
    displayToken = SurfaceComposerClient::getPhysicalDisplayToken(ids.front());
    
    // 获取屏幕相关参数
    ui::DisplayMode displayMode;
    err = SurfaceComposerClient::getActiveDisplayMode(displayToken, &displayMode);
    if (err != OK)
        return;    

    
    ui::Size resolution = displayMode.resolution; 
    resolution = limitSurfaceSize(resolution.width, resolution.height);

    // 创建 Surface
    sp<SurfaceControl> surfaceControl = surfaceComposerClient->createSurface(mName, resolution.getWidth(), 
                                                                             resolution.getHeight(), PIXEL_FORMAT_RGBA_8888,
                                                                             ISurfaceComposerClient::eFXSurfaceBufferState,
                                                                             /*parent*/ nullptr);

    // ......
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

上面的代码基本就以下几步:

  1. 建立 App 到 SurfaceFlinger 的 Binder 通信通道(上一节已经分析)
  2. 向 Client 匿名服务发起远程调用 SurfaceComposerClient::getPhysicalDisplayIds() 获取到显示设备的 ID,返回的是一个 vector,因为存在多屏或者投屏等情况
  3. 发起远程调用 SurfaceComposerClient::getPhysicalDisplayToken(ids.front()) 获取到显示设备的索引 displayToken
  4. 发起远程调用 SurfaceComposerClient::getActiveDisplayMode 获取到屏幕相关参数,返回的结果保存在 DisplayMode 对象中
  5. 最后发起远程调用 surfaceComposerClient->createSurface 创建 Surface,这个就有的说了

第 1 步上一节已经分析了,

2,3,4 步发起远程调用获取一些屏幕相关的配置信息,不是重点,了解一下即可。

第 5 步创建一个 SurfaceControl,这个很重要

# 3. SurfaceControl 构建过程分析

# 3.1 图层概念回顾

图层的概念之前说过,我们这里在回顾一下:

20240222122043

(图片来自 https://www.jianshu.com/p/b0ef7c04486d)

在很多的图形相关的软件中都有图层的概念,那什么是图层呢?

简单的说,可以将每个图层理解为一张透明的纸,将图像的各部分绘制在不同的透明纸(图层)上。透过这层纸,可以看到纸后面的东西,而且每层纸都是独立的,无论在这层纸上如何涂画,都不会影响到其他图层中的图像。也就是说,每个图层可以独立编辑或修改,最后将透明纸叠加起来,从上向下俯瞰,即可得到并实时改变最终的合成效果。

分析代码之前,我们先了解 SurfaceControl 创建过程中涉及到的类:

  • Surface 对象用于在 Native App 中描述一个图层,每一个 Surface 对象与 SurfaceControl 相关联,可以认为 Surface 和 SurfaceControl 是等价的
  • Layer 对象用于在 SurfaceFlinger 中描述一个图层。
  • 一个 Surface 对应一个 Layer

SurfaceFlinger 是一个独立的 Service, 它接收 Surface 作为输入,根据 Z-Order, 透明度,大小,位置等参数,构建一个对应的 Layer 对象,计算出每个 Layer 在最终合成图像中的位置,然后在 sf-Vysnc 信号到来时,sf 将 Layer 交给 HWComposer 生成最终的显示 Buffer, 然后显示到特定的显示设备上。

# 3.2 Layer 构建过程分析

我们的示例程序中使用如下的代码构建一个 SurfaceControl 对象:

    // 创建 Surface
    sp<SurfaceControl> surfaceControl = surfaceComposerClient->createSurface(mName, resolution.getWidth(), 
                                                                             resolution.getHeight(), PIXEL_FORMAT_RGBA_8888,
                                                                             ISurfaceComposerClient::eFXSurfaceBufferState,
                                                                             /*parent*/ nullptr);
1
2
3
4
5

createSurface 是一个远程调用函数,会调用到 SurfaceFligner 进程中 Client 对象的 createSurface 函数。

函数会返回一个 SurfaceControl 对象,SurfaceControl/Surface 在 Native App 端代表了一个图层,它的定义如下:

class SurfaceControl : public RefBase
{

// ......

private:
    // can't be copied
    SurfaceControl& operator = (SurfaceControl& rhs);
    SurfaceControl(const SurfaceControl& rhs);

    friend class SurfaceComposerClient;
    friend class Surface;

    ~SurfaceControl();

    sp<Surface> generateSurfaceLocked();
    status_t validate() const;

    // 应用创建的SurfaceComposerClient对象指针,里面封装了和SurfaceFlinger通信的Binder客户端对象
    sp<SurfaceComposerClient>   mClient;  
    // layer handle
    // 对应的 SF 进程中的 Layer 的索引
    sp<IBinder> mHandle;
    mutable Mutex               mLock;
    // SurfaceControl 对应的 Surface
    mutable sp<Surface>         mSurfaceData;  
    // BLASTBufferQueue 实例
    mutable sp<BLASTBufferQueue> mBbq; 
    // SurfaceControl 的子节点 ?
    mutable sp<SurfaceControl> mBbqChild;
    int32_t mLayerId = 0;
    std::string mName;
    uint32_t mTransformHint = 0;
    uint32_t mWidth = 0;
    uint32_t mHeight = 0;
    PixelFormat mFormat = PIXEL_FORMAT_NONE;
    uint32_t mCreateFlags = 0;
    uint64_t mFallbackFrameNumber = 100;
    std::shared_ptr<Choreographer> mChoreographer;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

这里关心它的几个重要成员,在注释中已做说明。

接下来我们来看 createSurface 函数的执行过程

// /frameworks/native/libs/gui/SurfaceComposerClient.cpp

sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
                                                        PixelFormat format, int32_t flags,
                                                        const sp<IBinder>& parentHandle,
                                                        LayerMetadata metadata,
                                                        uint32_t* outTransformHint) {
    sp<SurfaceControl> s;
    createSurfaceChecked(name, w, h, format, &s, flags, parentHandle, std::move(metadata),
                         outTransformHint);
    return s;
}
1
2
3
4
5
6
7
8
9
10
11
12

接着调用 createSurfaceChecked:

// /frameworks/native/libs/gui/include/gui/SurfaceComposerClient.h
sp<ISurfaceComposerClient>  mClient;

// /frameworks/native/libs/gui/SurfaceComposerClient.cpp
status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
                                                     PixelFormat format,
                                                     sp<SurfaceControl>* outSurface, int32_t flags,
                                                     const sp<IBinder>& parentHandle,
                                                     LayerMetadata metadata,
                                                     uint32_t* outTransformHint) {
    sp<SurfaceControl> sur;
    status_t err = mStatus;

    if (mStatus == NO_ERROR) {
        gui::CreateSurfaceResult result;
        
        // 发起远程调用
        // 创建 Layer
        // Layer 相关的信息通过参数 result 返回
        // 重点关注 result 中的 handle 成员
        binder::Status status = mClient->createSurface(std::string(name.string()), flags,
                                                       parentHandle, std::move(metadata), &result);
        err = statusTFromBinderStatus(status);
        if (outTransformHint) {
            *outTransformHint = result.transformHint;
        }
        ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
        if (err == NO_ERROR) {
            
            // 通过 Result 的参数 new 一个 SurfaceControl
            // 重点是 handle
            *outSurface = new SurfaceControl(this, result.handle, result.layerId,
                                             toString(result.layerName), w, h, format,
                                             result.transformHint, flags);
        }
    }
    return err;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

mClient 是匿名 Binder 服务 Client 的代理端对象,这里远程调用到 SurfaceFlinger 进程中的 createSurface 函数,最终会调用到服务端 Client 类的 createSurface 函数中。

远程调用 createSurface 会返回一个 gui::CreateSurfaceResult result 对象,接着会用这个对象中的成员构造一个 SurfaceControl 对象并返回。

接下来我们来看服务端的 createSurface 函数:

// /frameworks/native/services/surfaceflinger/Client.h
sp<SurfaceFlinger> mFlinger;

// /frameworks/native/services/surfaceflinger/Client.cpp
binder::Status Client::createSurface(const std::string& name, int32_t flags,
                                     const sp<IBinder>& parent, const gui::LayerMetadata& metadata,
                                     gui::CreateSurfaceResult* outResult) {

    // We rely on createLayer to check permissions.
    sp<IBinder> handle;
    LayerCreationArgs args(mFlinger.get(), sp<Client>::fromExisting(this), name.c_str(),
                           static_cast<uint32_t>(flags), std::move(metadata));
    // handle 放到了 LayerCreationArgs 中,这个 handle 是我们即将要创建的 Layer 的父 Layer 的索引
    // 需要注意的是 CreateSurfaceResult 中也有一个 handle,这个是我们要创建的 Layer 的索引
    args.parentHandle = parent;
    // 接着调用 SurfaceFlinger 的 createLayer 函数
    const status_t status = mFlinger->createLayer(args, *outResult);
    return binderStatusFromStatusT(status);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

createSruface 中会接着调用 SurfaceFlinger 的 createLayer 函数,createlayer 函数的两个参数分别是 LayerCreationArgs 和 CreateSurfaceResult

LayerCreationArgs 是创建 Layer 相关的参数。

// /frameworks/native/services/surfaceflinger/FrontEnd/LayerCreationArgs.h

struct LayerCreationArgs {
    static std::atomic<uint32_t> sSequence;
    static std::atomic<uint32_t> sInternalSequence;
    static uint32_t getInternalLayerId(uint32_t id);
    static LayerCreationArgs fromOtherArgs(const LayerCreationArgs& other);

    LayerCreationArgs(android::SurfaceFlinger*, sp<android::Client>, std::string name,
                      uint32_t flags, gui::LayerMetadata, std::optional<uint32_t> id = std::nullopt,
                      bool internalLayer = false);
    LayerCreationArgs(std::optional<uint32_t> id, bool internalLayer = false);
    LayerCreationArgs() = default; // for tracing
    std::string getDebugString() const;

    android::SurfaceFlinger* flinger;
    sp<android::Client> client;
    std::string name;
    uint32_t flags; // ISurfaceComposerClient flags
    gui::LayerMetadata metadata;
    pid_t ownerPid;
    uid_t ownerUid;
    uint32_t textureName;
    uint32_t sequence;
    bool addToRoot = true;
    wp<IBinder> parentHandle = nullptr;
    wp<IBinder> mirrorLayerHandle = nullptr;
    ui::LayerStack layerStackToMirror = ui::INVALID_LAYER_STACK;
    uint32_t parentId = UNASSIGNED_LAYER_ID;
    uint32_t layerIdToMirror = UNASSIGNED_LAYER_ID;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

CreateSurfaceResult 用于保存 Layer 的相关信息,继承自 Parcelable,可以通过 Binder 传输。

class CreateSurfaceResult : public ::android::Parcelable {
public:
  ::android::sp<::android::IBinder> handle;
  int32_t layerId = 0;
  ::android::String16 layerName;
  int32_t transformHint = 0;
    // ......
}
1
2
3
4
5
6
7
8

createSurface 函数中的 CreateSurfaceResult 以参数的形式返回给客户端。

SurfaceFlinger 的 createLayer 函数实现如下:

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, gui::CreateSurfaceResult& outResult) {
    status_t result = NO_ERROR;

    sp<Layer> layer;

    // flags 的值为  ISurfaceComposerClient::eFXSurfaceBufferState
    switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
        case ISurfaceComposerClient::eFXSurfaceBufferQueue:
        case ISurfaceComposerClient::eFXSurfaceContainer:
        case ISurfaceComposerClient::eFXSurfaceBufferState:    // 走这个 case 
            args.flags |= ISurfaceComposerClient::eNoColorFill;  
            FMT_FALLTHROUGH;
        case ISurfaceComposerClient::eFXSurfaceEffect: { // 上面没有 break,这个 case 也会走
            // 创建 Layer 对象
            // args 中有个 handle 
            // 第二个参数也是一个 handle
            result = createBufferStateLayer(args, &outResult.handle, &layer);
            std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
            if (pendingBufferCounter) {
                std::string counterName = layer->getPendingBufferCounterName();
                mBufferCountTracker.add(outResult.handle->localBinder(), counterName,
                                        pendingBufferCounter);
            }
        } break;
        default:
            result = BAD_VALUE;
            break;
    }

    if (result != NO_ERROR) {
        return result;
    }

    args.addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
    // We can safely promote the parent layer in binder thread because we have a strong reference
    // to the layer's handle inside this scope.
    // 使用 args.parentHandle 索引找到 Layer 的父节点
    sp<Layer> parent = LayerHandle::getLayer(args.parentHandle.promote());
    if (args.parentHandle != nullptr && parent == nullptr) {
        ALOGE("Invalid parent handle %p", args.parentHandle.promote().get());
        args.addToRoot = false;
    }

    uint32_t outTransformHint;

    // add a layer to SurfaceFlinger
    // 把 Layer 对象添加到 SurfaceFlinger
    result = addClientLayer(args, outResult.handle, layer, parent, &outTransformHint);
    if (result != NO_ERROR) {
        return result;
    }

    outResult.transformHint = static_cast<int32_t>(outTransformHint);
    outResult.layerId = layer->sequence;
    outResult.layerName = String16(layer->getDebugName());
    return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

这里主要关注 createBufferStateLayer 的过程:

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
                                                sp<Layer>* outLayer) {
    args.textureName = getNewTexture();
    *outLayer = getFactory().createBufferStateLayer(args);
    *handle = (*outLayer)->getHandle();
    return NO_ERROR;
}
1
2
3
4
5
6
7
8

这里通过工厂模式创建 BufferStateLayer,分析代码实现之前我们先看看 Layer 相关的类,这些类设计都比较复杂,直接分析代码会比较懵。

先看 Layer 的定义,

// /frameworks/native/services/surfaceflinger/Layer.h
class Layer : public virtual RefBase {
    // ......
    void onFirstRef() override;
    // .....
}
1
2
3
4
5
6

Layer 用于在 SurfaceFlinger 中表示一个图层,Layer 类继承自 RefBase 类,可以使用 Android 平台的 sp wp 管理 Layer 指针。其内部定义了 onFirstRef 对象,在首次引用时会被调用

Layer 中还有个重要的内部类 State,从名字就可以看出,State 用于描述一个 Layer 对象的状态。

State 内部参数很多,我们挑重要的讲:

    struct State {

        // z 坐标轴的值
        int32_t z;
        /*
         Android 系统支持多种显示设备,比如说,输出到手机屏幕,或者通过WiFi 投射到电视屏幕。Android用DisplayDevice类来表示这样的设备。不是所有的Layer都会输出到所有的Display, 比如说,我们可以只将Video Layer投射到电视, 而非整个屏幕。LayerStack 就是为此设计,LayerStack 是一个Display 对象的一个数值, 而类Layer里成员State结构体也有成员变量mLayerStack, 只有两者的mLayerStack 值相同,Layer才会被输出到给该Display设备。所以LayerStack 决定了每个Display设备上可以显示的Layer数目。   
        */
        ui::LayerStack layerStack;
        uint32_t flags;
        // / Layer 的序列号,每次图元的属性发生改变时,这个序列号都需要自增
        int32_t sequence; // changes when visible regions can change
        bool modified;
        // Crop is expressed in layer space coordinate.
        Rect crop;
        LayerMetadata metadata;
        // If non-null, a Surface this Surface's Z-order is interpreted relative to.
        wp<Layer> zOrderRelativeOf;
        bool isRelativeOf{false};

        // A list of surfaces whose Z-order is interpreted relative to ours.
        SortedVector<wp<Layer>> zOrderRelatives;
        half4 color;
        float cornerRadius;
        int backgroundBlurRadius;
        gui::WindowInfo inputInfo;
        wp<Layer> touchableRegionCrop;

        ui::Dataspace dataspace;

        uint64_t frameNumber;
        // high watermark framenumber to use to check for barriers to protect ourselves
        // from out of order transactions
        uint64_t barrierFrameNumber;
        ui::Transform transform;

        uint32_t producerId = 0;
        // high watermark producerId to use to check for barriers to protect ourselves
        // from out of order transactions
        uint32_t barrierProducerId = 0;

        uint32_t bufferTransform;
        bool transformToDisplayInverse;
        Region transparentRegionHint;
        std::shared_ptr<renderengine::ExternalTexture> buffer;
        sp<Fence> acquireFence;
        std::shared_ptr<FenceTime> acquireFenceTime;
        HdrMetadata hdrMetadata;
        Region surfaceDamageRegion;
        int32_t api;
        sp<NativeHandle> sidebandStream;
        mat4 colorTransform;
        bool hasColorTransform;
        // pointer to background color layer that, if set, appears below the buffer state layer
        // and the buffer state layer's children.  Z order will be set to
        // INT_MIN
        sp<Layer> bgColorLayer;

        // The deque of callback handles for this frame. The back of the deque contains the most
        // recent callback handle.
        std::deque<sp<CallbackHandle>> callbackHandles;
        bool colorSpaceAgnostic;
        nsecs_t desiredPresentTime = 0;
        bool isAutoTimestamp = true;

        // Length of the cast shadow. If the radius is > 0, a shadow of length shadowRadius will
        // be rendered around the layer.
        float shadowRadius;

        // Layer regions that are made of custom materials, like frosted glass
        std::vector<BlurRegion> blurRegions;

        // Priority of the layer assigned by Window Manager.
        int32_t frameRateSelectionPriority;

        // Default frame rate compatibility used to set the layer refresh rate votetype.
        FrameRateCompatibility defaultFrameRateCompatibility;
        FrameRate frameRate;

        // The combined frame rate of parents / children of this layer
        FrameRate frameRateForLayerTree;

        // Set by window manager indicating the layer and all its children are
        // in a different orientation than the display. The hint suggests that
        // the graphic producers should receive a transform hint as if the
        // display was in this orientation. When the display changes to match
        // the layer orientation, the graphic producer may not need to allocate
        // a buffer of a different size. ui::Transform::ROT_INVALID means the
        // a fixed transform hint is not set.
        ui::Transform::RotationFlags fixedTransformHint;

        // The vsync info that was used to start the transaction
        FrameTimelineInfo frameTimelineInfo;

        // When the transaction was posted
        nsecs_t postTime;
        sp<ITransactionCompletedListener> releaseBufferListener;
        // SurfaceFrame that tracks the timeline of Transactions that contain a Buffer. Only one
        // such SurfaceFrame exists because only one buffer can be presented on the layer per vsync.
        // If multiple buffers are queued, the prior ones will be dropped, along with the
        // SurfaceFrame that's tracking them.
        std::shared_ptr<frametimeline::SurfaceFrame> bufferSurfaceFrameTX;
        // A map of token(frametimelineVsyncId) to the SurfaceFrame that's tracking a transaction
        // that contains the token. Only one SurfaceFrame exisits for transactions that share the
        // same token, unless they are presented in different vsyncs.
        std::unordered_map<int64_t, std::shared_ptr<frametimeline::SurfaceFrame>>
                bufferlessSurfaceFramesTX;
        // An arbitrary threshold for the number of BufferlessSurfaceFrames in the state. Used to
        // trigger a warning if the number of SurfaceFrames crosses the threshold.
        static constexpr uint32_t kStateSurfaceFramesThreshold = 25;

        // Stretch effect to apply to this layer
        StretchEffect stretchEffect;

        // Whether or not this layer is a trusted overlay for input
        bool isTrustedOverlay;
        Rect bufferCrop;
        Rect destinationFrame;
        sp<IBinder> releaseBufferEndpoint;
        gui::DropInputMode dropInputMode;
        bool autoRefresh = false;
        bool dimmingEnabled = true;
        float currentHdrSdrRatio = 1.f;
        float desiredHdrSdrRatio = 1.f;
        gui::CachingHint cachingHint = gui::CachingHint::Enabled;
        int64_t latchedVsyncId = 0;
        bool useVsyncIdForRefreshRateSelection = false;
    };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

Layer 中有一个 State mDrawingState; 成员,用于描述 Layer 的 State

回过头来在分析创建 Layer 的过程

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
                                                sp<Layer>* outLayer) {
    args.textureName = getNewTexture();
    *outLayer = getFactory().createBufferStateLayer(args);
    *handle = (*outLayer)->getHandle();
    return NO_ERROR;
}

surfaceflinger::Factory& getFactory() { return mFactory; }
1
2
3
4
5
6
7
8
9
10

mFactory 在哪里初始化呢?

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
      : mFactory(factory), // 这里赋值
        mPid(getpid()),
        mTimeStats(std::make_shared<impl::TimeStats>()),
        mFrameTracer(mFactory.createFrameTracer()),
        mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
        mCompositionEngine(mFactory.createCompositionEngine()),
        mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
        mTunnelModeEnabledReporter(sp<TunnelModeEnabledReporter>::make()),
        mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
        mInternalDisplayDensity(
                getDensityFromProperty("ro.sf.lcd_density", !mEmulatedDisplayDensity)),
        mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
        mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
    ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

那 SurfaceFliger 又在哪里初始化呢?

// /frameworks/native/services/surfaceflinger/main_surfaceflinger.cpp
int main(int, char**) {
    // ......
    // instantiate surfaceflinger
    sp<SurfaceFlinger> flinger = surfaceflinger::createSurfaceFlinger();
    // ......
}

// /frameworks/native/services/surfaceflinger/SurfaceFlingerFactory.cpp
sp<SurfaceFlinger> createSurfaceFlinger() {
    static DefaultFactory factory;

    return sp<SurfaceFlinger>::make(factory);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

终于找到了,传入的是 DefaultFactory 对象, 接下来看 DefaultFactory 中 createBufferStateLayer 函数的实现:

sp<Layer> DefaultFactory::createBufferStateLayer(const LayerCreationArgs& args) {
    return sp<Layer>::make(args);
}
1
2
3

就是简单 new 一个 layer,layer 的构造函数实现如下:

// /frameworks/native/services/surfaceflinger/Layer.cpp

Layer::Layer(const LayerCreationArgs& args)
      : sequence(args.sequence),
        mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
        mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
        mClientRef(args.client),
        mWindowType(static_cast<WindowInfo::Type>(
                args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
        mLayerCreationFlags(args.flags),
        mBorderEnabled(false),
        mTextureName(args.textureName),
        mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {

    ALOGV("Creating Layer %s", getDebugName());

    uint32_t layerFlags = 0;
    if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
    if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
    if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
    if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
        layerFlags |= layer_state_t::eLayerSkipScreenshot;
    mDrawingState.flags = layerFlags;  // if 应该都不会成立,这里都是 0
    mDrawingState.crop.makeInvalid();
    mDrawingState.z = 0;
    mDrawingState.color.a = 1.0f;
    mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
    mDrawingState.sequence = 0;
    mDrawingState.transform.set(0, 0);
    mDrawingState.frameNumber = 0;
    mDrawingState.barrierFrameNumber = 0;
    mDrawingState.producerId = 0;
    mDrawingState.barrierProducerId = 0;
    mDrawingState.bufferTransform = 0;
    mDrawingState.transformToDisplayInverse = false;
    mDrawingState.crop.makeInvalid();
    mDrawingState.acquireFence = sp<Fence>::make(-1);
    mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
    mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
    mDrawingState.hdrMetadata.validTypes = 0;
    mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
    mDrawingState.cornerRadius = 0.0f;
    mDrawingState.backgroundBlurRadius = 0;
    mDrawingState.api = -1;
    mDrawingState.hasColorTransform = false;
    mDrawingState.colorSpaceAgnostic = false;
    mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
    mDrawingState.metadata = args.metadata;
    mDrawingState.shadowRadius = 0.f;
    mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
    mDrawingState.frameTimelineInfo = {};
    mDrawingState.postTime = -1;
    mDrawingState.destinationFrame.makeInvalid();
    mDrawingState.isTrustedOverlay = false;
    mDrawingState.dropInputMode = gui::DropInputMode::NONE;
    mDrawingState.dimmingEnabled = true;
    mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;

    if (args.flags & ISurfaceComposerClient::eNoColorFill) {
        // Set an invalid color so there is no color fill.
        mDrawingState.color.r = -1.0_hf;
        mDrawingState.color.g = -1.0_hf;
        mDrawingState.color.b = -1.0_hf;
    }

    mFrameTracker.setDisplayRefreshPeriod(
            args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());

    mOwnerUid = args.ownerUid;
    mOwnerPid = args.ownerPid;

    mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
    mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
    mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;

    // Layer 的快照,后续合成会用
    mSnapshot->sequence = sequence;
    mSnapshot->name = getDebugName();
    mSnapshot->textureName = mTextureName;
    mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
    mSnapshot->parentTransform = {};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

构造函数主要就是给 mDrawingState 成员初始化,mDrawingState 用于表示 Layer 的状态。

还有个很重要的点,Layer 构建完成后,会调用 Layer 的 getHandle 函数,返回一个 handle 给客户端:

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
                                                sp<Layer>* outLayer) {
    args.textureName = getNewTexture();
    *outLayer = getFactory().createBufferStateLayer(args);
    // 调用 handle
    *handle = (*outLayer)->getHandle();
    return NO_ERROR;
}


sp<IBinder> Layer::getHandle() {
    Mutex::Autolock _l(mLock);
    if (mGetHandleCalled) {
        ALOGE("Get handle called twice" );
        return nullptr;
    }
    mGetHandleCalled = true;
    mHandleAlive = true;
    return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

这里 new 一个 LayerHandle 返回, LayerHandle 的实现如下:

// /frameworks/native/services/surfaceflinger/FrontEnd/LayerHandle.h
class LayerHandle : public BBinder {
public:
    LayerHandle(const sp<android::SurfaceFlinger>& flinger, const sp<android::Layer>& layer);
    // for testing
    LayerHandle(uint32_t layerId) : mFlinger(nullptr), mLayer(nullptr), mLayerId(layerId) {}
    ~LayerHandle();

    // Static functions to access the layer and layer id safely from an incoming binder.
    static sp<LayerHandle> fromIBinder(const sp<IBinder>& handle);
    static sp<android::Layer> getLayer(const sp<IBinder>& handle);
    static uint32_t getLayerId(const sp<IBinder>& handle);
    static const String16 kDescriptor;

    const String16& getInterfaceDescriptor() const override { return kDescriptor; }

private:
    sp<android::SurfaceFlinger> mFlinger;
    sp<android::Layer> mLayer;
    const uint32_t mLayerId;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

handle 的类型是 LayerHandle,是一个 Binder 服务端对象。这个 handle 最终会返回给 App 端,是一个索引,app 可以将其传递给 sf 找到对应的 Layer。

接着会调用到 SurfaceFlinger::addClientLayer:

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.h
    std::vector<LayerCreatedState> mCreatedLayers GUARDED_BY(mCreatedLayersLock);
    std::vector<std::unique_ptr<frontend::RequestedLayerState>> mNewLayers;
    std::vector<LayerCreationArgs> mNewLayerArgs;

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
status_t SurfaceFlinger::addClientLayer(LayerCreationArgs& args, const sp<IBinder>& handle,
                                        const sp<Layer>& layer, const wp<Layer>& parent,
                                        uint32_t* outTransformHint) {

    if (mNumLayers >= MAX_LAYERS) { // Layer 过多的处理
        // ......
    }

    layer->updateTransformHint(mActiveDisplayTransformHint);
    if (outTransformHint) {
        *outTransformHint = mActiveDisplayTransformHint;
    }
    args.parentId = LayerHandle::getLayerId(args.parentHandle.promote());
    args.layerIdToMirror = LayerHandle::getLayerId(args.mirrorLayerHandle.promote());
    {
        std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
        // layer 相关信息放到这里,下次 VSync 信号到来,读取这些数据配置新的 Layer 对象
        mCreatedLayers.emplace_back(layer, parent, args.addToRoot);
        // 创建 Layer 的参数
        mNewLayers.emplace_back(std::make_unique<frontend::RequestedLayerState>(args));
        args.mirrorLayerHandle.clear();
        args.parentHandle.clear();
        mNewLayerArgs.emplace_back(std::move(args));
    }

    setTransactionFlags(eTransactionNeeded); // 0x01
    return NO_ERROR;   
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

实际就是把新创建的 Layer 及相关信息保存到 SurfaceFlinger 的成员变量中。其中最重要的成员是 mCreatedLayers,当下次 VSync 信号到来,读取这些数据配置新的 Layer 对象并合成显示。

Layer 创建完成后,就会逐级返回到 createSurfaceChecked 函数中。


// /frameworks/native/libs/gui/include/gui/SurfaceComposerClient.h
sp<ISurfaceComposerClient>  mClient;

// /frameworks/native/libs/gui/SurfaceComposerClient.cpp
status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
                                                     PixelFormat format,
                                                     sp<SurfaceControl>* outSurface, int32_t flags,
                                                     const sp<IBinder>& parentHandle,
                                                     LayerMetadata metadata,
                                                     uint32_t* outTransformHint) {
    sp<SurfaceControl> sur;
    status_t err = mStatus;

    if (mStatus == NO_ERROR) {
        gui::CreateSurfaceResult result;
        
        // 创建 Layer
        // Layer 相关的信息通过参数 result 返回,result 中保存了 layer 相关的信息,最重要的是 handle ,handle 是一个索引,能找到对应的 Layer 对象
        binder::Status status = mClient->createSurface(std::string(name.string()), flags,
                                                       parentHandle, std::move(metadata), &result);
        err = statusTFromBinderStatus(status);
        if (outTransformHint) {
            *outTransformHint = result.transformHint;
        }
        ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
        if (err == NO_ERROR) {
            
            // 通过 Result 中的信息创建 SurfaceControl
            *outSurface = new SurfaceControl(this, result.handle, result.layerId,
                                             toString(result.layerName), w, h, format,
                                             result.transformHint, flags);
        }
    }
    return err;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

接下来会通过 Result 中的信息创建一个 SurfaceControl 对象,SurfaceControl 的构造函数实现如下:

SurfaceControl::SurfaceControl(const sp<SurfaceComposerClient>& client, const sp<IBinder>& handle,
                               int32_t layerId, const std::string& name, uint32_t w, uint32_t h,
                               PixelFormat format, uint32_t transform, uint32_t flags)
      : mClient(client),
        mHandle(handle),
        mLayerId(layerId),
        mName(name),
        mTransformHint(transform),
        mWidth(w),
        mHeight(h),
        mFormat(format),
        mCreateFlags(flags) {}
1
2
3
4
5
6
7
8
9
10
11
12

主要就是给内部成员赋值。

小结一下:

  • App 发起远程调用 createSurface
  • 在 sf 进程中就创建好了 Layer 对象
  • 在 App 进程中利用 createSurface 创建好了 SurfaceControl 对象,SurfaceControl 中有一个 mHandle 成员可以索引到对应的 Layer 对象中。

# 4. SurfaceComposerClient 提交事务过程

有了 SurfaceControl 后,就可以进行申请 buffer,绘制图形,提交 buffer 等操作了。

但是如果想要配置图层的 zorder,位置等属性怎么办呢?

在 SurfaceComposerClient::Transaction 中提供了各中配置属性的方法 SurfaceComposerClient::Transaction::setXXX()

接着看后面的代码:

    SurfaceComposerClient::Transaction{}
            .setLayer(surfaceControl, std::numeric_limits<int32_t>::max())
            .show(surfaceControl)
            .setBackgroundColor(surfaceControl, half3{0, 0, 0}, 1.0f, ui::Dataspace::UNKNOWN) // black background
            .setAlpha(surfaceControl, 1.0f)
            .setLayerStack(surfaceControl, ui::LayerStack::fromValue(mLayerStack)) // mLayerStack 的值为 0
            .apply();
1
2
3
4
5
6
7

开启一个事务,远程设置 Layer。

这里会先 new 一个 SurfaceComposerClient::Transaction 对象,Transaction 有一个重要的成员 mComposerStates:

    class Transaction : public Parcelable {
        // .....
        std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> mComposerStates;

        std::unordered_map<sp<ITransactionCompletedListener>, CallbackInfo, TCLHash>
                mListenerCallbacks;
        // ......
    }
1
2
3
4
5
6
7
8

mComposerStates 是一个 map,key 是窗口的 token, value 是 ComposerState,用于保存窗口的配置信息:

class ComposerState {
public:
    layer_state_t state;
    status_t write(Parcel& output) const;
    status_t read(const Parcel& input);
};
1
2
3
4
5
6

layer_state_t 是一个结构体,用于在 SurfaceFlinger 与 app 之间交换 layer 相关的数据。

/*
 * Used to communicate layer information between SurfaceFlinger and its clients.
 */
struct layer_state_t {

// ......
    sp<IBinder> surface;
    int32_t layerId;
    uint64_t what;
    float x;
    float y;
    int32_t z;
    ui::LayerStack layerStack = ui::DEFAULT_LAYER_STACK;
    uint32_t flags;
    uint32_t mask;
    uint8_t reserved;
    matrix22_t matrix;
    float cornerRadius;
    uint32_t backgroundBlurRadius;

    sp<SurfaceControl> relativeLayerSurfaceControl;

    sp<SurfaceControl> parentSurfaceControlForChild;

    half4 color;

    // non POD must be last. see write/read
    Region transparentRegion;
    uint32_t bufferTransform;
    bool transformToDisplayInverse;
    Rect crop;
    std::shared_ptr<BufferData> bufferData = nullptr;
    ui::Dataspace dataspace;
    HdrMetadata hdrMetadata;
    Region surfaceDamageRegion;
    int32_t api;
    sp<NativeHandle> sidebandStream;
    mat4 colorTransform;
    std::vector<BlurRegion> blurRegions;

    sp<gui::WindowInfoHandle> windowInfoHandle = sp<gui::WindowInfoHandle>::make();

    LayerMetadata metadata;

    // The following refer to the alpha, and dataspace, respectively of
    // the background color layer
    half4 bgColor;
    ui::Dataspace bgColorDataspace;
// .....

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

先看 setLayer 的实现:

// /frameworks/native/libs/gui/SurfaceComposerClient.cpp

SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayer(
        const sp<SurfaceControl>& sc, int32_t z) {
    layer_state_t* s = getLayerState(sc);
    if (!s) {
        mStatus = BAD_INDEX;
        return *this;
    }
    s->what |= layer_state_t::eLayerChanged;
    s->what &= ~layer_state_t::eRelativeLayerChanged;
    s->z = z;

    registerSurfaceControlForCallback(sc);
    return *this;
}

std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> mComposerStates;

layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
    
    // 窗口 token
    auto handle = sc->getLayerStateHandle();

    if (mComposerStates.count(handle) == 0) {
        // we don't have it, add an initialized layer_state to our list
        ComposerState s;

        s.state.surface = handle;
        s.state.layerId = sc->getLayerId();

        mComposerStates[handle] = s;
    }

    return &(mComposerStates[handle].state);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

实际就是把配置信息写到 mComposerStates 成员中。

setPosition 的实现:

SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setPosition(
        const sp<SurfaceControl>& sc, float x, float y) {
    layer_state_t* s = getLayerState(sc);
 
    s->what |= layer_state_t::ePositionChanged;
    s->x = x;
    s->y = y;
 
    return *this;
}
1
2
3
4
5
6
7
8
9
10

别的设置属性的实现基本都差不多,不再一一阐述。

设置完一堆参数后,调用 apply :

// 两个参数默认是 false
status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay) {
    if (mStatus != NO_ERROR) {
        return mStatus;
    }

    std::shared_ptr<SyncCallback> syncCallback = std::make_shared<SyncCallback>();
    if (synchronous) {
        syncCallback->init();
        addTransactionCommittedCallback(SyncCallback::getCallback(syncCallback),
                                        /*callbackContext=*/nullptr);
    }

    bool hasListenerCallbacks = !mListenerCallbacks.empty();
    std::vector<ListenerCallbacks> listenerCallbacks;
    // For every listener with registered callbacks
    for (const auto& [listener, callbackInfo] : mListenerCallbacks) {
        auto& [callbackIds, surfaceControls] = callbackInfo;
        if (callbackIds.empty()) {
            continue;
        }

        if (surfaceControls.empty()) {
            listenerCallbacks.emplace_back(IInterface::asBinder(listener), std::move(callbackIds));
        } else {
            // If the listener has any SurfaceControls set on this Transaction update the surface
            // state
            for (const auto& surfaceControl : surfaceControls) {
                layer_state_t* s = getLayerState(surfaceControl);
                if (!s) {
                    ALOGE("failed to get layer state");
                    continue;
                }
                std::vector<CallbackId> callbacks(callbackIds.begin(), callbackIds.end());
                s->what |= layer_state_t::eHasListenerCallbacksChanged;
                s->listeners.emplace_back(IInterface::asBinder(listener), callbacks);
            }
        }
    }

    cacheBuffers();

    Vector<ComposerState> composerStates;
    Vector<DisplayState> displayStates;
    uint32_t flags = 0;

    for (auto const& kv : mComposerStates) {
        composerStates.add(kv.second);
    }

    displayStates = std::move(mDisplayStates);

    if (mAnimation) {
        flags |= ISurfaceComposer::eAnimation;
    }
    if (oneWay) {
        if (synchronous) {
            ALOGE("Transaction attempted to set synchronous and one way at the same time"
                  " this is an invalid request. Synchronous will win for safety");
        } else {
            flags |= ISurfaceComposer::eOneWay;
        }
    }

    // If both mEarlyWakeupStart and mEarlyWakeupEnd are set
    // it is equivalent for none
    if (mEarlyWakeupStart && !mEarlyWakeupEnd) {
        flags |= ISurfaceComposer::eEarlyWakeupStart;
    }
    if (mEarlyWakeupEnd && !mEarlyWakeupStart) {
        flags |= ISurfaceComposer::eEarlyWakeupEnd;
    }

    sp<IBinder> applyToken = mApplyToken ? mApplyToken : sApplyToken;

    sp<ISurfaceComposer> sf(ComposerService::getComposerService());
    // 关键
    sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken,
                            mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp,
                            mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId,
                            mMergedTransactionIds);
    mId = generateId();

    // Clear the current states and flags
    clear();

    if (synchronous) {
        syncCallback->wait();
    }

    mStatus = NO_ERROR;
    return NO_ERROR;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

这里 sf->setTransactionState 发起远程调用,最终会 Binder 远程调用到 SurfaceFlinger 的 setTransactionState:

// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
status_t SurfaceFlinger::setTransactionState(
        const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& states,
        const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
        InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp,
        const std::vector<client_cache_t>& uncacheBuffers, bool hasListenerCallbacks,
        const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId,
        const std::vector<uint64_t>& mergedTransactionIds) {
   

    // ......

    // ComposerState 转换为 ResolvedComposerState
    std::vector<ResolvedComposerState> resolvedStates;
    resolvedStates.reserve(states.size());
    for (auto& state : states) {
        resolvedStates.emplace_back(std::move(state));
        auto& resolvedState = resolvedStates.back();
        if (resolvedState.state.hasBufferChanges() && resolvedState.state.hasValidBuffer() &&
            resolvedState.state.surface) {
            sp<Layer> layer = LayerHandle::getLayer(resolvedState.state.surface);
            std::string layerName = (layer) ?
                    layer->getDebugName() : std::to_string(resolvedState.state.layerId);
            resolvedState.externalTexture =
                    getExternalTextureFromBufferData(*resolvedState.state.bufferData,
                                                     layerName.c_str(), transactionId);
            mBufferCountTracker.increment(resolvedState.state.surface->localBinder());
        }
        resolvedState.layerId = LayerHandle::getLayerId(resolvedState.state.surface);
        if (resolvedState.state.what & layer_state_t::eReparent) {
            resolvedState.parentId =
                    getLayerIdFromSurfaceControl(resolvedState.state.parentSurfaceControlForChild);
        }
        if (resolvedState.state.what & layer_state_t::eRelativeLayerChanged) {
            resolvedState.relativeParentId =
                    getLayerIdFromSurfaceControl(resolvedState.state.relativeLayerSurfaceControl);
        }
        if (resolvedState.state.what & layer_state_t::eInputInfoChanged) {
            wp<IBinder>& touchableRegionCropHandle =
                    resolvedState.state.windowInfoHandle->editInfo()->touchableRegionCropHandle;
            resolvedState.touchCropId =
                    LayerHandle::getLayerId(touchableRegionCropHandle.promote());
        }
    }

    // 构建一个 TransactionState
    TransactionState state{frameTimelineInfo,
                           resolvedStates,
                           displays,
                           flags,
                           applyToken,
                           std::move(inputWindowCommands),
                           desiredPresentTime,
                           isAutoTimestamp,
                           std::move(uncacheBufferIds),
                           postTime,
                           hasListenerCallbacks,
                           listenerCallbacks,
                           originPid,
                           originUid,
                           transactionId,
                           mergedTransactionIds};


    if (mTransactionTracing) {
        mTransactionTracing->addQueuedTransaction(state);
    }

    const auto schedule = [](uint32_t flags) {
        if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
        if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
        return TransactionSchedule::Late;
    }(state.flags);

    // 关注点
    const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
    mTransactionHandler.queueTransaction(std::move(state));
    setTransactionFlags(  , schedule, applyToken, frameHint);
    return NO_ERROR;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

先通过传入的参数构建一个 TransactionState 对象,接着调用 queueTransaction,将创建的 state 放入 mLocklessTransactionQueue 队列,mPendingTransactionCount 加 1;下一个 vsync 信号到来时,就会把 TransactionState 对象取出来并加以应用。

// /frameworks/native/services/surfaceflinger/FrontEnd/TransactionHandler.h
LocklessQueue<TransactionState> mLocklessTransactionQueue;

// /frameworks/native/services/surfaceflinger/FrontEnd/TransactionHandler.cpp
void TransactionHandler::queueTransaction(TransactionState&& state) {
    mLocklessTransactionQueue.push(std::move(state));
    mPendingTransactionCount.fetch_add(1);
    ATRACE_INT("TransactionQueue", static_cast<int>(mPendingTransactionCount.load()));
}
1
2
3
4
5
6
7
8
9

app 向 surfaceflinger 提交事务之后,surfaceflinger 会缓存事务;当 vsync 到来之后,会取出事务并处理,这个我们会在 Vsync 的章节来讲解。

# 总结

  • 远程调用获取显示配置信息
  • App 向 SF 发起远程调用,SF 中创建一个 Layer 对象,App 中创建一个 SurfaceControl 对象,SurfaceControl 对象中有一个 mHandle 成员,该成员可以索引到 Layer 对象
  • 通过事务远程配置 Layer,SF 中构建好 TransactionState 对象,等待 vsync 到来,取出对象并应用

# 参考资料